/*
 * @lc app=leetcode.cn id=592 lang=cpp
 *
 * [592] 分数加减运算
 */

// @lc code=start
class Solution {
public:
    bool isDigit(char c) { return c >= '0' && c <= '9'; }
    int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
    string fractionAddition(string expression) {
        int n = expression.size(), numerator = 0, denominator = 1, idx = 0;
        while (idx < n) {
            int sign = 1;
            if (expression[idx] == '-' || expression[idx] == '+') {
                sign = expression[idx] == '-' ? -1 : 1;
                idx++;
            }

            int num = 0;
            while (idx < n && isDigit(expression[idx])) {
                num = num * 10 + (expression[idx] - '0');
                idx++;
            }
            num *= sign;

            idx++;

            int den = 0;
            while (idx < n && isDigit(expression[idx])) {
                den = den * 10 + (expression[idx] - '0');
                idx++;
            }

            numerator = numerator * den + num * denominator;
            denominator *= den;
        }

        if (numerator == 0) return "0/1";

        int g = gcd(abs(numerator), denominator);

        return to_string(numerator / g) + "/" + to_string(denominator / g);
    }
};
// @lc code=end
